import React, { Component } from 'react';
import store from './store/index';
import { increase, decrease, async_increase } from './store/actionCreators'

class App extends Component {
  constructor(props) {
    super(props)
    // 获取state
    this.state = store.getState();

    // 绑定this
    this.handleStoreChange = this.handleStoreChange.bind(this)
    // 订阅store的改变
    store.subscribe(this.handleStoreChange)
  }

  render() {
    const { count } = this.state
    return (
      <div>
        {count} <br />
        <button onClick={() => this.add()}>增加</button>
        <button onClick={() => this.dsc()}>减少</button>
        <button onClick={() => this.asyncAdd()}>异步增加</button>
      </div>
    );
  }

  // 添加方法
  add() {
    store.dispatch(increase())
  }

  // 减少方法
  dsc() {
    store.dispatch(decrease())
  }

  asyncAdd() {
    store.dispatch(async_increase())
  }

  handleStoreChange() {
    this.setState(store.getState())
  }
}

export default App